import { useAlarmWebsocketHook } from "@/store/modules/alarmWebSocket";
import Cookies from "js-cookie";
import { storageLocal } from "@pureadmin/utils";
const audio = new Audio("/audio/5c88e51168d3728345.mp3");
const ws = () => {
  const token = JSON.parse(Cookies.get("authorized-token")).token;
  const webSocket = new WebSocket("ws://192.168.2.203:8989/api/ws", token);

  webSocket.onopen = () => {
    console.log("连接成功");
    webSocket.send('{"action":"alarm_popup"}');
    webSocket.send('{"action":"alarm_notify"}');
  };

  //重连锁
  let lockReconnect = false;

  const reconnect = () => {
    if (lockReconnect) return;
    lockReconnect = true;
    setTimeout(function () {
      //没连接上会一直重连，设置延迟避免请求过多
      ws();
      lockReconnect = false;
    }, 5000);
  };

  webSocket.onclose = () => {
    console.log("连接关闭");
  };

  webSocket.onerror = (error: any) => {
    reconnect();
    console.log("连接错误!", error);
  };

  webSocket.onmessage = (res: any) => {
    const configData =
      storageLocal().getItem("configData") ||
      ({
        open_alarm_popup: true,
        open_alarm_prompt: true,
        open_alarm_voice: true
      } as any);
    const data = JSON.parse(res.data);
    if (data.action === "alarm_popup") {
      useAlarmWebsocketHook().alarmData = JSON.parse(res.data).payload;
      if (configData.open_alarm_prompt && configData.open_alarm_popup) {
        useAlarmWebsocketHook().alarmPopUpsFlag = true;
        setTimeout(() => {
          useAlarmWebsocketHook().alarmPopUpsFlag = false;
        }, 5200);
      }
      if (configData.open_alarm_prompt && configData.open_alarm_voice) {
        audio.play();
      }
    }
    if (data.action === "alarm_notify") {
      useAlarmWebsocketHook().alarmNotify = JSON.parse(res.data).payload;
    }
  };
  return webSocket;
};

export default ws;
